package com.pai4j.common.util;

import com.pai4j.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

@Slf4j
public class FileConvertUtil {

    /** 默认转换后文件后缀 */
    private static final String DEFAULT_SUFFIX = "pdf";
    /** openoffice_port */
    private static final Integer OPENOFFICE_PORT = 8100;

    /***
     * File --> MultipartFile
     * @param file
     * @return
     */
    public static MultipartFile convertFileToMultipartFile(File file) {
        try {
            FileInputStream input = new FileInputStream(file);
            return new MockMultipartFile("file", file.getName(), "text/plain",
                    IOUtils.toByteArray(input));
        } catch (Exception e) {
            log.error("convert file to MultipartFile error. fileName:{}", file.getName(), e);
        }
        return null;
    }

    /***
     * BufferedImage 转 MultipartFile
     * @param image
     * @return
     */
    public static MultipartFile convertBufferedImageToMultipartFile(BufferedImage image) {
        try {
            // BufferedImage 转化为 ByteArrayOutputStream
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", out);
            // ByteArrayOutputStream 转化为 byte[]
            byte[] imageByte = out.toByteArray();
            // 将 byte[] 转为 MultipartFile
            String name = FileUtil.generateFileName(System.currentTimeMillis() + ".jpg");
            return convertByteArrayToMultipartFile(name, imageByte);
        } catch (Exception e) {
            log.error("convert file to MultipartFile error.", e);
        }
        return null;
    }

    public static InputStream convertLocaleFile2Stream(String sourcePath) throws Exception {
        File inputFile = new File(sourcePath);
        return new FileInputStream(inputFile);
    }

    /***
     * 二进制文件转换为 MultipartFile
     * @param bytes
     * @return
     */
    public static MultipartFile convertByteArrayToMultipartFile(String name, byte[] bytes) {
        try (InputStream inputStream = new ByteArrayInputStream(bytes)) {
            return convertInputStreamToMultipartFile(name, inputStream);
        } catch (IOException e) {
            log.error("convert byte array to MultipartFile error.", e);
        }
        return null;
    }

    public static MultipartFile convertBufferImageToMultipartFile(BufferedImage bufferedImage) {
        //创建一个ByteArrayOutputStream
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        //把BufferedImage写入ByteArrayOutputStream
        try {
            ImageIO.write(bufferedImage, "png", os);
            //ByteArrayOutputStream转成InputStream
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            //InputStream转成MultipartFile
            String name = IDGenerateUtil.createId("codelink");
            return new MockMultipartFile(name, name+".png", ContentType.APPLICATION_OCTET_STREAM.toString(), input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new BusinessException("图片转换异常");
    }

    /***
     * 文件流转换为 MultipartFile
     * @param name 文件名称
     * @param inputStream 文件流
     * @return
     */
    public static MultipartFile convertInputStreamToMultipartFile(String name, InputStream inputStream) {
        MockMultipartFile mockMultipartFile = null;
        try {
            mockMultipartFile = new MockMultipartFile(name, name,
                    ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
        } catch (IOException e) {
            log.error("convert inputStream to MultipartFile error.", e);
        }
        return mockMultipartFile;
    }

    /***
     * MultipartFile转换为二进制
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public static byte[] convertMultipartFileToByteArray(MultipartFile multipartFile) {
        byte[] binary = new byte[0];
        try {
            binary = multipartFile.getBytes();
        } catch (Exception e) {
            log.error("convert MultipartFile to byte array error.", e);
        }
        return binary;
    }

    public static BufferedImage convertByteArray2BufferImage(byte[] b) {
        //将b作为输入流；
        ByteArrayInputStream in = new ByteArrayInputStream(b);
        //将in作为输入流，读取图片存入image中，而这里in可以为ByteArrayInputStream();
        try {
            return ImageIO.read(in);
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 方法描述 outputStream转inputStream
     *
     * @author tarzan
     */
    public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception {
        ByteArrayOutputStream baos=(ByteArrayOutputStream) out;
        return new ByteArrayInputStream(baos.toByteArray());
    }

    /**
     * inputStream转为byte[]
     *
     * @param inStream
     * @return byte[]
     * @throws IOException
     */
    public static byte[] convert2ByteArray(InputStream inStream) {
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int rc = 0;
            while ((rc = inStream.read(buff, 0, 1024)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            // in_b为转换之后的结果
            return swapStream.toByteArray();
        } catch (Exception e) {
            return new byte[0];
        }
    }

    public static void main(String[] args) throws IOException {
        //convertNetFile("http://172.16.10.21/files/home/upload/department/base/201912090541573c6abdf2394d4ae3b7049dcee456d4f7.doc", ".pdf");
        //convert("c:/Users/api/Desktop/2.pdf", "c:/Users/api/Desktop/3.pdf");
    }
}
